package cn.com.ddapp.ddm.fragment.base;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.bumptech.glide.Glide;
import com.zhy.autolayout.AutoFrameLayout;
import com.zhy.autolayout.AutoLinearLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.com.ddapp.ddm.AppConfig;
import cn.com.ddapp.ddm.MainActivity;
import cn.com.ddapp.ddm.R;
import cn.com.ddapp.ddm.adapter.BrandRevelryAdapter;
import cn.com.ddapp.ddm.adapter.ClassifyAdapter;
import cn.com.ddapp.ddm.adapter.FeatureAdapter;
import cn.com.ddapp.ddm.adapter.GuessAdapter;
import cn.com.ddapp.ddm.adapter.HomePagerAdapter;
import cn.com.ddapp.ddm.api.OKUtilAPI;
import cn.com.ddapp.ddm.base.BaseApplication;
import cn.com.ddapp.ddm.bean.AreaBean;
import cn.com.ddapp.ddm.bean.Banner;
import cn.com.ddapp.ddm.bean.HomeBean;
import cn.com.ddapp.ddm.inter.OkUtilCallback;
import cn.com.ddapp.ddm.ui.BrandListActivity;
import cn.com.ddapp.ddm.ui.CitysListActivity;
import cn.com.ddapp.ddm.ui.CommidContentActivity;
import cn.com.ddapp.ddm.ui.CommonScanActivity;
import cn.com.ddapp.ddm.ui.GoodClassifyActivity;
import cn.com.ddapp.ddm.ui.LimitTimeGoActivity;
import cn.com.ddapp.ddm.ui.PermissionsActivity;
import cn.com.ddapp.ddm.ui.PermissionsChecker;
import cn.com.ddapp.ddm.ui.PromotioActivity;
import cn.com.ddapp.ddm.ui.SearchActivity;
import cn.com.ddapp.ddm.ui.empty.EmptyLayout;
import cn.com.ddapp.ddm.ui.mine.InfoCenterActivity;
import cn.com.ddapp.ddm.util.BannerUtil;
import cn.com.ddapp.ddm.util.Constant;
import cn.com.ddapp.ddm.util.CountDownProTimer;
import cn.com.ddapp.ddm.util.CountDownTimer;
import cn.com.ddapp.ddm.util.HomeBannerUtil;
import cn.com.ddapp.ddm.util.NetUtils;
import cn.com.ddapp.ddm.util.SPUtils;
import cn.com.ddapp.ddm.util.TDevice;
import cn.com.ddapp.ddm.util.TLog;
import cn.com.ddapp.ddm.util.Utility;
import cn.com.ddapp.ddm.widget.pulltorefresh.PullToRefreshLayout;
import cn.com.ddapp.ddm.widget.pulltorefresh.pullableview.PullableLinearyout;
import cn.com.ddapp.ddm.widget.pulltorefresh.pullableview.PullableRecyclerview;
import cn.com.ddapp.ddm.widget.pulltorefresh.pullableview.PullableScrollView;
import okhttp3.Call;

import static com.umeng.socialize.editorpage.ShareActivity.REQUEST_CODE;

/**
 * Created by Administrator on 2016/8/16 0016.
 */
public class HomePagerFragment extends BaseFragment implements View.OnClickListener, AMapLocationListener {
    @BindView(R.id.homePager)
    ViewPager homePager;
    @BindView(R.id.weiText)
    TextView weiText;
    @BindView(R.id.classRcycler)
    PullableRecyclerview classRcycler;
    @BindView(R.id.tiseRecycler)
    PullableRecyclerview tiseRecycler;
    @BindView(R.id.revelry)
    PullableRecyclerview revelry;
    @BindView(R.id.buttomView)
    PullableRecyclerview buttomView;
    @BindView(R.id.error_layout)
    EmptyLayout mEmptyLayout;
    @BindView(R.id.lifefayout)
    AutoLinearLayout lifefayout;
    @BindView(R.id.rightLayput)
    AutoFrameLayout rightLayput;
    @BindView(R.id.erwei)
    ImageView erwei;
    @BindView(R.id.xiaoImage)
    ImageView xiaoImage;
    @BindView(R.id.end_layout)
    RelativeLayout endLayout;
    @BindView(R.id.tosortList)
    RelativeLayout tosortList;
    @BindView(R.id.downImage)
    ImageView downImage;
    @BindView(R.id.llDots)
    LinearLayout llDots;
    @BindView(R.id.timerrView)
    CountDownProTimer timerView;
    @BindView(R.id.frameLayout)
    AutoFrameLayout frameLayout;
    @BindView(R.id.bannerview)
    RelativeLayout bannerview;
    @BindView(R.id.area_tese)
    TextView area_tese;
    @BindView(R.id.share_refresh)
    PullToRefreshLayout share_refresh;
    @BindView(R.id.home_scrollview)
    PullableScrollView home_scrollview;
    private LocationSource.OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private HomeBean homeBean;
    private int position;
    public int perPosition;
    private List<HomeBean.BannerListBean> bannerListBeen;
    private List<HomeBean.PromotionListBean> promotionList;
    private List<HomeBean.GuessListBean> guessListBeen;
    private List<ImageView> ivs = new ArrayList<>();
    private Intent intent;
    private boolean Looper = true;
    private boolean isRun = true;
    private long mHour = 13;
    private long mMin = 00;
    private long mSecond = 00;
    private int promotionId;
    private ArrayList<Banner> bannerBean = new ArrayList<>();
    private PermissionsChecker mPermissionsChecker; // 权限检测器
    // 所需的全部权限
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE
    };
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    try {
                        //得到当前viewpager的位置索引
                        int currentItem = homePager.getCurrentItem();
                        homePager.setCurrentItem(currentItem + 1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };
    private List<HomeBean.SortListBean> sortList;
    private List<HomeBean.BrandListBean> brandList;

    private void startRun() {
        timerView.setTime(3, 15, 33);
        timerView.start();
    }

    @Override
    protected String getFragmentTag() {
        return null;
    }

    @Override
    protected void initData() {
        mPermissionsChecker = new PermissionsChecker(getActivity());
        share_refresh.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                initNetData(AppConfig.CITY_ID);
                share_refresh.refreshFinish(PullToRefreshLayout.SUCCEED);
            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
//                initNetNewData();
                share_refresh.loadmoreFinish(PullToRefreshLayout.NODATA);
            }
        });
        int width = (int) (TDevice.getScreenWidth());
        int height = (int) (TDevice.getScreenWidth() / 2);
//        LinearLayout.LayoutParams  params=new LinearLayout.LayoutParams(width,height);
//        frameLayout.setLayoutParams(params);
//        int pheight=frameLayout.getLayoutParams().height;
//        int pwidth=frameLayout.getLayoutParams().width;

//        AutoFrameLayout.LayoutParams pp=new AutoFrameLayout.LayoutParams(width,height);
//        bannerview.setLayoutParams(pp);

//        bannerview.getLayoutParams().width=width;
//        bannerview.getLayoutParams().height=height;
        if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
            startPermissionsActivity();
        }else{
            location();
        }
    }
    private void startPermissionsActivity() {
        PermissionsActivity.startActivityForResult(getActivity(), REQUEST_CODE, PERMISSIONS);
    }
    private void location() {
        //声明mLocationOption对象
        mlocationClient = new AMapLocationClient(getActivity());
//初始化定位参数
        mLocationOption = new AMapLocationClientOption();
//设置定位监听
        mlocationClient.setLocationListener(this);
//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
//设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
// 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
// 在定位结束后，在合适的生命周期调用onDestroy()方法
// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
//启动定位
        mlocationClient.startLocation();
        System.out.println("开启定位");
    }


    private void initNetData(final int addrId) {
        if (!NetUtils.isConnected(getContext())) {
            Toast.makeText(getContext(), "请检查你的网络", Toast.LENGTH_SHORT).show();
        } else {
            mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
            OkUtilCallback okUtilCallback = new OkUtilCallback(mEmptyLayout) {
                @Override
                public void onMyResponse(String response, int id) {
//                    TLog.log(getFragmentTag(), response);
                    homeBean = gson.fromJson(response, HomeBean.class);
                    if ((!AppConfig.RESULT_OK.equalsIgnoreCase(homeBean.getResult()))) {
                        BaseApplication.getIntstance().showToast(homeBean.getResult(), Toast.LENGTH_SHORT, 0, Gravity.TOP);
                    } else if ((AppConfig.RESULT_OK.equalsIgnoreCase(homeBean.getResult()))) {
                        initGoodsClassify();//物品分类
                        initshoreData();//特色专享
                        initBrandRevelry();//品牌狂欢
                        initLoveGoods();//猜你喜欢
//                        initTopViewPager();//头部的viewpager轮播
                        initBanner();
                        if(AppConfig.CITY_ID == 182){
                            SPUtils.setStringData(getContext(), SPUtils.AREANAME, "丰城市");
                        }else{

                        }
                        String curName = SPUtils.getStringData(getContext(), SPUtils.AREANAME);
                        area_tese.setText(curName + ".特色专享");
                        weiText.setText(curName);
                    }
                }

                @Override
                public void onError(Call call, Exception e, int id) {
                    super.onError(call, e, id);
                    mEmptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
                }
            };
            OKUtilAPI.get(OKUtilAPI.homeurl + "?addrId=" + addrId, "", okUtilCallback);
        }
    }

    private void initBanner() {
        if (homeBean.getBannerList() != null) {
            bannerBean = homeBean.getBannerList();
            bannerview.removeAllViews();
            ArrayList<Banner> banners = new ArrayList<>();
            for (int i = 0; i < bannerBean.size(); i++) {
                Banner banner = new Banner();
                banner.setImgPath(OKUtilAPI.imgBaseUrl + bannerBean.get(i).getImg());
                banner.setImgUrl(bannerBean.get(i).getImg());
                banner.setLink(bannerBean.get(i).getLink());
                banners.add(banner);
            }
            bannerview.addView(HomeBannerUtil.getloopviewpager2(getActivity(), banners,"home"));
        }
    }

    private void initLoveGoods() {
        guessListBeen = homeBean.getGuessList();
        GuessAdapter guessAdapter = new GuessAdapter(getContext(), guessListBeen);
        buttomView.setAdapter(guessAdapter);
        buttomView.setLayoutManager(new LinearLayoutManager(getContext()));
        guessAdapter.setOnItemClickListener(new GuessAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                intent = new Intent(getContext(), CommidContentActivity.class);
                int id = guessListBeen.get(position).getId();

//              Log.e("ID", "ID===========" + id);
                intent.putExtra("type","id");
                intent.putExtra("id", String.valueOf(id));
                AppConfig.TOMAIN = "2";
                startActivity(intent);
            }

            @Override
            public void onItemLongClick(View v, int position) {

            }
        });
    }

    private void initBrandRevelry() {
        brandList = homeBean.getBrandList();
        BrandRevelryAdapter bAdapter = new BrandRevelryAdapter(getContext(), brandList);
        revelry.setAdapter(bAdapter);
        revelry.setLayoutManager(new GridLayoutManager(getContext(), 3, LinearLayoutManager.VERTICAL, false));
        bAdapter.setOnItemClickListener(new BrandRevelryAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int i) {
                Intent intent = new Intent(getActivity(), GoodClassifyActivity.class);
                intent.putExtra("brandId", brandList.get(i).getId());
//                intent.putExtra("brandId",nList.get(i).getId());
                String lId = brandList.get(i).getId() + "";
                SPUtils.setStringData(getActivity(), SPUtils.LID, lId);
                AppConfig.TOMAIN = "2";
                startActivity(intent);
            }

            @Override
            public void onItemLongClick(View v, int position) {

            }
        });
    }

    private void initshoreData() {
        if (homeBean.getPromotionList().size() > 0) {
            final List<HomeBean.PromotionListBean> promotionList = homeBean.getPromotionList();
            if (promotionList.size() > 0) {
                promotionId = homeBean.getPromotionList().get(0).getId();
                tiseRecycler.setVisibility(View.VISIBLE);
                FeatureAdapter featureAdapter = new FeatureAdapter(getContext(), promotionList);
                tiseRecycler.setAdapter(featureAdapter);
                tiseRecycler.setLayoutManager(new GridLayoutManager(getContext(), 3, LinearLayoutManager.VERTICAL, false));
                featureAdapter.setOnItemClickListener(new FeatureAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(View v, int position) {
                        Intent intent = new Intent(getContext(), CommidContentActivity.class);
                        int id = promotionList.get(0).getGoodsList().get(position).getId();
//                    Log.e("IDS", "ID===========" + id);
                        intent.putExtra("type","id");
                        intent.putExtra("id", String.valueOf(id));
                        AppConfig.TOMAIN = "2";
                        startActivity(intent);
                    }

                    @Override
                    public void onItemLongClick(View v, int position) {

                    }
                });
            } else {
                tiseRecycler.setVisibility(View.GONE);
            }

        } else {
            tiseRecycler.setVisibility(View.GONE);
        }
    }

    private void initGoodsClassify() {
        sortList = homeBean.getSortList();
        ClassifyAdapter classifyAdapter = new ClassifyAdapter(getContext(), sortList);
        classRcycler.setAdapter(classifyAdapter);
        classRcycler.setLayoutManager(new GridLayoutManager(getContext(), 5, LinearLayoutManager.VERTICAL, false));
        classifyAdapter.setOnItemClickListener(new ClassifyAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                Intent intent = new Intent(getContext(), GoodClassifyActivity.class);
                String lId = sortList.get(position).getLevelId();
                SPUtils.setStringData(getActivity(), SPUtils.LID, lId);
                intent.putExtra("claName", sortList.get(position).getName());
                intent.putExtra("classiftId", sortList.get(position).getLevelId());
                AppConfig.TOMAIN = "2";
                startActivity(intent);
//                if(position==9){
//                    ((MainActivity)getActivity()).showSortPageFragment();
//                }
            }

            @Override
            public void onItemLongClick(View v, int position) {

            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        System.out.println("huag==onResume");
        if (AppConfig.APPFVISIT.equals("2")) {
            initNetData(AppConfig.CITY_ID);
            if(mlocationClient.isStarted()){
                mlocationClient.stopLocation();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        mMapView.onDestroy();
        mlocationClient.stopLocation();
        Looper = false;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        startRun();//开启倒计时
        mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
    }

    private void initgetAddId(final double lat, final double log) {
        final OkUtilCallback okUtilCallback = new OkUtilCallback() {
            @Override
            public void onMyResponse(String response, int id) {
                AreaBean bean = gson.fromJson(response, AreaBean.class);
                if (!bean.getResult().equals("OK")) {
                    BaseApplication.showToast(bean.getResult());
                    SPUtils.setStringData(getContext(), SPUtils.AREANAME, "丰城");
                } else {
                    AreaBean.IndexArea a = bean.getArea();
                    AppConfig.CITY_ID = a.getId();
                    AppConfig.WID = a.getId();
                    SPUtils.setStringData(getContext(), SPUtils.AREANAME, a.getName());
                    initNetData(a.getId());
                    AppConfig.APPFVISIT = "2";
                    Log.i("aaa", "---a--" + AppConfig.CITY_ID + a.getName());
                }
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                mEmptyLayout.setErrorType(EmptyLayout.NODATA_ENABLE_CLICK);
            }
        };
        String params = "longitude=" + log + "&latitude=" + lat;
        OKUtilAPI.post(OKUtilAPI.indexaddId, params, okUtilCallback);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @OnClick({R.id.lifefayout, R.id.erwei, R.id.xiaoImage, R.id.end_layout, R.id.tosortList,
            R.id.downImage, R.id.morepinpai, R.id.rightLayput, R.id.weiText, R.id.img_error_layout})
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.lifefayout:
                intent = new Intent(getContext(), LimitTimeGoActivity.class);
                startActivity(intent);
                break;
            case R.id.erwei:
                intent = new Intent(getContext(), CommonScanActivity.class);
                intent.putExtra(Constant.REQUEST_SCAN_MODE, Constant.REQUEST_SCAN_MODE_ALL_MODE);
                startActivity(intent);
                break;
            case R.id.xiaoImage:
                intent = new Intent(getActivity(), InfoCenterActivity.class);
                startActivity(intent);
                break;
            case R.id.end_layout:
                intent = new Intent(getContext(), SearchActivity.class);
                startActivity(intent);
                break;
            case R.id.weiText:
                intent = new Intent(getContext(), CitysListActivity.class);
                startActivity(intent);
                break;
            case R.id.downImage://切换城市
                intent = new Intent(getContext(), CitysListActivity.class);
                startActivity(intent);
                break;
            case R.id.tosortList:
                Log.i("aaa", "--promotionId-" + promotionId);
                intent = new Intent(getContext(), GoodClassifyActivity.class);
                intent.putExtra("claName", area_tese.getText().toString());
                intent.putExtra("promotionId", promotionId);
                startActivity(intent);
                break;
            case R.id.morepinpai:
                intent = new Intent(getContext(), BrandListActivity.class);
                startActivity(intent);
                break;
            case R.id.rightLayput:
                intent = new Intent(getContext(), PromotioActivity.class);
                startActivity(intent);
                break;
            case R.id.img_error_layout:
                initNetData(AppConfig.CITY_ID);
                break;
        }
    }
//    private void setUpMap() {
//        aMap.setLocationSource(this);// 设置定位监听
//        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
//        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
//        // 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
//        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
//    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        System.out.println("定位返回");
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                double lat = amapLocation.getLatitude();
                double log = amapLocation.getLongitude();
                Log.i("aaa", "---prohomelatt--" + lat + "--" + log);
                AppConfig.LAT = lat;
                AppConfig.LNG = log;
//                AppConfig.City_NAME=amapLocation.getDistrict();
                if (AppConfig.APPFVISIT.equals("1")) {
                    initgetAddId(lat, log);//第一次访问通过定位获取地址ID
                } else {
                    initNetData(AppConfig.CITY_ID);
                }
            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo() + amapLocation.getLocationDetail();
                Log.i("Toshare", errText);
                BaseApplication.showToast(errText);
                initNetData(AppConfig.CITY_ID);
            }
        } else {
            initNetData(AppConfig.CITY_ID);
        }
        mlocationClient.stopLocation();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 拒绝时, 关闭页面, 缺少主要权限, 无法运行
        if (requestCode == REQUEST_CODE && resultCode == PermissionsActivity.PERMISSIONS_DENIED) {
            location();
        }else if(requestCode == REQUEST_CODE && resultCode == PermissionsActivity.PERMISSIONS_GRANTED){
            try {
               location();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
